  <template>
    <div>
      <Window :show="windowConfig.show" :buttons="windowConfig.buttons" @close="closeWindow">
        <el-form :rules="rules" :model="blogFormData" ref="blogFormRef">
          <el-form-item prop="title">
            <div class="input_title">
              <el-input placeholder="请输入博客标题" v-model="blogFormData.title"></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="content">
            <div :style="{ 'width': '100%' }">
              <EditorHtml v-if="blogFormData.editorType === 0" :height="editorHtmlHeight"
                v-model="blogFormData.content">
              </EditorHtml>
              <EditorMarkdown v-else @htmlContent="setHtmlContent" :height="editorMarkdownHeight"
                v-model="blogFormData.markdownContent">
              </EditorMarkdown>
            </div>
          </el-form-item>
        </el-form>

        <!-- <EditorHtml :height="editorHtmlHeight"></EditorHtml> -->

        <Dialog width="800px" :show="dialogConfig.show" @close="dialogConfig.show = false" :title="dialogConfig.title"
          :buttons="dialogConfig.buttons">
          <el-form :model=blogFormData :rules="rules" ref="settingsFormRef" label-width='80px'
            class="blog_setting_form">
            <el-form-item label="博客分类" prop="categoryId">
              <el-select :style="{ width: '100%' }" v-model="blogFormData.categoryId" clearable placeholder="请选择分类">
                <el-option :value=0 label="全部分类"></el-option>
                <el-option v-for="item in categoryList" :key="item.id" :value="item.categoryId"
                  :label="item.categoryName"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="封面" prop="cover">
              <CoverUpload v-model="blogFormData.cover"></CoverUpload>
            </el-form-item>

            <el-form-item label="博客类型" prop="type">
              <el-radio-group v-model="blogFormData.type">
                <el-radio :value="0">原创</el-radio>
                <el-radio :value="1">转载</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="原文链接" prop="reprintUrl" v-if="blogFormData.type == 0">
              <el-input placeholder="请输入原文链接" v-model="blogFormData.reprintUrl">
              </el-input>
            </el-form-item>

            <el-form-item label="评论" prop="allowComment">
              <div class="allow_comment">
                <el-radio-group v-model="blogFormData.allowComment">
                  <el-radio :value="1">允许</el-radio>
                  <el-radio :value="0">不允许</el-radio>
                </el-radio-group>
                <span class="info">请先在评论设置里设置好相应的参数，评论才会生效</span>
              </div>
            </el-form-item>

            <el-form-item label="博客摘要" prop="summary">
              <el-input type="textarea" placeholder="请输入摘要" v-model="blogFormData.summary" size="large"
                :autosize="{ minRows: 4, maxRows: 4 }">
              </el-input>
            </el-form-item>

            <el-form-item label="博客标签" prop="tag">
              <div class="tag_input_panel">
                <div class="tag_list">
                  <el-tag v-for="(item, index) in blogFormData.tag" @close="closeTag(index)" closable class="tag_item">
                    {{ item }}
                  </el-tag>
                </div>
                <span class="info" v-if="blogFormData.tag.length == 0">添加标签更容易被搜索引擎收录</span>
                <span class="iconfont icon-upload" @click="showTagInputHandler" v-if="!showTagInput"></span>
                <el-input class="tag_input" v-if="showTagInput" v-model="tagInputValue" @blur="tagInputResult"
                  @keyup.enter="tagInputResult"></el-input>
              </div>
            </el-form-item>
          </el-form>
        </Dialog>
      </Window>
    </div>
  </template>

<script setup>
import { getCurrentInstance, nextTick, onMounted, onUnmounted, proxyRefs, reactive, ref } from 'vue'
const { proxy } = getCurrentInstance();
const rules = {
  title: [{
    required: true, message: '请输入标题'
  }],
  categoryId: [{
    required: true, message: '请选择博客分类'
  }],
  content: [{
    required: true, message: '请选择输入正文'
  }],
  type: [{
    required: true, message: '请选择博客类型'
  }],
  allowComment: [{
    required: true, message: '请选择是否允许评论'
  }],
  reprintUrl: [{
    required: true, message: '请输入原文地址'
  }],
}

const editorMarkdownHeight = window.innerHeight - 60 - 20 - 30 - 50 - 10 - 50
const editorHtmlHeight = window.innerHeight - 60 - 20 - 30 - 50 - 100

const api = {
  'loadAllCategory4Blog': 'category/loadAllCategory4Blog',
  'saveBlog': 'blog/saveBlog',
  'getUserInfo': 'getUserInfo',
  'getBlogDetail': 'blog/getBlogById',
  'autoSave': 'blog/autoSaveBlog'
}

const init = (type, data) => {
  startTimer();
  windowConfig.show = true;
  nextTick(() => {
    blogFormRef.value.resetFields();
    blogFormData.value = { tag: [] };
    if (type === 'add') {
      getUserInfo();
    } else {
      getBlogDetail(data.blogId)
    }
  })
}

defineExpose({
  init
})

const getUserInfo = async () => {
  let res = await proxy.Request({
    url: api.getUserInfo,
  })
  if (!res) {
    return;
  }
  blogFormData.value.editorType = res.data.editorType
}

const getBlogDetail = async (blogId) => {
  let res = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId
    }
  })
  if (!res) {
    return;
  }
  blogFormData.value = res.data
  if (res.data.tag) {
    blogFormData.value.tag = res.data.tag.split('|')
  } else {
    blogFormData.value.tag = [];
  }
}

let timer = ref(null);
const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 10000)
}

const clearTimer = () => {
  if (timer.value !== null) {
    clearInterval(timer.value)
    timer.value == null
  }
}

// 自动保存
const autoSave = async () => {
  if (blogFormData.value.title == undefined || blogFormData.value.content == undefined || dialogConfig.show || timer.value == null) {
    return;
  }
  const params = {}
  Object.assign(params, blogFormData.value)
  let res = await proxy.Request({
    url: api.autoSave,
    params,
  })
  if (res) {
    return;
  }
  blogFormData.value.blogId = res.data
}

const windowConfig = reactive({
  show: false,
  buttons: [{
    type: 'danger',
    text: '确定',
    click: (e) => {
      showSettings();
    }
  }]
})


const emit = defineEmits();
const closeWindow = () => {
  windowConfig.show = false;
  emit('callback');
  if (timer.value !== null) {
    clearTimer();
  }
}


// 第一步提交
const blogFormRef = ref(null)
const blogFormData = ref({ tag: [] });
// markdown编辑器，设置html内容
const setHtmlContent = (htmlContent) => {
  blogFormData.value.content = htmlContent
}


const showSettings = () => {
  blogFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    dialogConfig.show = true
  })
}

const dialogConfig = reactive({
  show: false,
  title: '',
  buttons: [{
    type: 'danger',
    text: '确定',
    click: (e) => {
      console.log('123');
      submitBlog();
      loadCategory();
    }
  }]
})

const categoryList = ref([])

const loadCategory = async () => {
  let res = await proxy.Request({
    url: api.loadAllCategory4Blog
  })
  if (!res) {
    return
  }
  categoryList.value = res.data
}

onMounted(() => {
  loadCategory();
})

onUnmounted(() => {
  clearTimer();
})

// 删除标签
const closeTag = (index) => {
  blogFormData.value.tag.splice(index, 1)
}

const showTagInput = ref(false)

const showTagInputHandler = (e) => {
  showTagInput.value = true
}

const tagInputValue = ref(null)

const tagInputResult = () => {
  if (tagInputValue.value == undefined) {
    return;
  }
  showTagInput.value = false;
  if (blogFormData.value.tag.indexOf(tagInputValue.value) == -1) {
    blogFormData.value.tag.push(tagInputValue.value);
  }
  tagInputValue.value = undefined;

}

const settingsFormRef = ref();
const submitBlog = () => {
  settingsFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    const params = {
    }
    Object.assign(params, blogFormData.value);
    params.tag = params.tag.join('|')

    let res = await proxy.Request({
      url: api.saveBlog,
      showLoading: false,
      params
    })
    if (!res) {
      return;
    }
    proxy.Message.success('保存博客成功')
    dialogConfig.show = false
    closeWindow();
  })
}
</script>

<style lang='scss'>
.input_title {
  width: 100%;
  border-bottom: 1px solid #ddd;

  .el-input {
    .el-input__wrapper {
      box-shadow: none;

      input {
        font-size: 18px;
      }
    }
  }
}

.blog_setting_form {
  .allow_comment {
    display: flex;

    .info {
      margin-left: 10px;
      color: #a3a3a3;
      font-size: 13px;
    }
  }

  .tag_input_panel {
    display: flex;
    align-items: center;

    .tag_list {
      display: flex;

      .tag_item {
        margin-right: 10px;

      }
    }

    .info {
      color: #a3a3a3;
      margin-right: 10px;
      font-size: 13px;
    }

    .icon-upload {
      margin-right: 10px;
      color: red;
      cursor: pointer;
    }

    .tag_input {
      width: 100px;
    }
  }

}
</style>